var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');

router.get('/', function(req, res, next) {
   res.render('test/index', {});  
});
router.get('/login', function(req, res, next) {
  res.render('test/login', {});  
});
router.post('/setToken',function(req, res, next) {
  console.log(req.body)
  const token = jwt.sign({ id: 2 }, 'process.env.SECRET_KEY', {
    expiresIn: 60 * 60 // token有效期为1小时
  });
  res.status(200).send({
    auth: true,
    token: token
  });  
})  
function verifyToken(req, res, next) {
  // 从请求头中获取token
    const token = req.headers['authorization'];
    if (!token) {
        return res.status(401).send({
        auth: false,
        message: 'No token provided.'
        });
    }
    // 验证token是否有效
    jwt.verify(token, 'process.env.SECRET_KEY', (err, decoded) => {
        if (err) {
        return res.status(500).send({
            auth: false,
            message: 'Failed to authenticate token.'
        });
        }
        // 将解码的用户信息存储到请求对象中
        req.userId = decoded.id;
        next();
    });
}
router.get('/verify', verifyToken, function(req, res, next) {
  res.send({
      auth: true,
      uid: req.userId
  })
});

module.exports = router;